package com.example.demo.modules.test.dto.student;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 读取监听器
 */
@Slf4j
//该类不需要被spring管理，如果需要存储至数据库可通过构造方法传入service或dao
public class StudentImportDTOReadListener implements ReadListener<StudentImportDTO> {

    //缓存的数据
    private List<StudentImportDTO> list = new ArrayList<>();

    public List<StudentImportDTO> getList() {
        return list;
    }

    public StudentImportDTOReadListener(){
        super();
    }

    //每一条数据解析都会来调用此方法
    @Override
    public void invoke(StudentImportDTO studentImportDTO, AnalysisContext analysisContext) {
        //easyExcel是逐行读取，每读取一行就放到集合里；
        //如果导入数据不多，可以读取结束后，再统一入库
        list.add(studentImportDTO);
    }

    //所有数据解析完了都会调用此方法
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("所有数据解析完毕！");
    }

    //可读取表头数据
    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        for (Integer key : headMap.keySet()) {
            System.out.println("key:" + key + " value:" + headMap.get(key).getStringValue());
        }
        System.out.println("=============");
    }

    //可读取备注数据
    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        if(extra.getType().equals(CellExtraTypeEnum.COMMENT)){
            System.out.println("行：" + (extra.getRowIndex() + 1));
            System.out.println("列：" + (extra.getColumnIndex() + 1));
            System.out.println("备注内容：" + extra.getText());
        }
    }
}
